package com.aggregate.pay.pufa.support;

import java.util.Base64;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aggregate.pay.pufa.support.utils.AES;
import com.aggregate.pay.pufa.support.utils.HEX;
import com.aggregate.pay.pufa.support.utils.RSA;

/**
 * 浦发代付接口签名工具类
 * @author Moyq5
 * @date 2019年1月3日
 */
public class Tool {
	
	private static Logger log = LoggerFactory.getLogger(Tool.class);
	
	public static boolean rsaVerify(String data, String sign, String key) {
		log.debug("浦发->验签值：{}", sign);
		log.debug("浦发->验签内容：{}", data);
		try {
			//byte[] signBytes = Base64.getDecoder().decode(sign);// base64
			byte[] signBytes = HEX.toByteArray(sign.toLowerCase());// hex
			return RSA.verify(data.getBytes("UTF-8"), signBytes, Base64.getDecoder().decode(key));
		} catch (Exception e) {
			log.error("浦发->验签失败", e);
			return false;
		}
	}
	
	public static String rsaSign(String data, String privateKey) {
		log.debug("浦发->签名内容：{}", data);
		try {
			byte[] signBytes = RSA.sign(data.getBytes("UTF-8"), Base64.getDecoder().decode(privateKey));
			//return Base64.getEncoder().encodeToString(signBytes);// base64
			return HEX.toHexString(signBytes).toLowerCase();// hex
		} catch (Exception e) {
			log.error("浦发->签名异常", e);
		}
		log.debug("浦发->签名值：{}", data);
		return data;
	}

	public static String rsaSignBase64(String data, String privateKey) {
		log.debug("浦发->签名内容：{}", data);
		try {
			byte[] signBytes = RSA.sign(data.getBytes("UTF-8"), Base64.getDecoder().decode(privateKey));
			return Base64.getEncoder().encodeToString(signBytes);// base64
			//return HEX.toHexString(signBytes);// hex
		} catch (Exception e) {
			log.error("浦发->签名异常", e);
		}
		log.debug("浦发->签名值：{}", data);
		return data;
	}

	public static byte[] rsaDecrypt(String data, String privateKey) {
		try {
			return RSA.decrypt(Base64.getDecoder().decode(data), Base64.getDecoder().decode(privateKey));
		} catch (Exception e) {
			log.error("浦发->解密异常", e);
		}
		return null;
	}
	
	public static String aesEncrypt(String data, byte[] pwd) {
		try {
			return Base64.getEncoder().encodeToString(AES.encrypt(data.getBytes("UTF-8"), pwd));
		} catch (Exception e) {
			log.error("浦发->加密异常", e);
		}
		return null;
	}

	public static String aesDecrypt(String data, byte[] pwd) {
		try {
			return new String(AES.decrypt(Base64.getDecoder().decode(data), pwd), "UTF-8");
		} catch (Exception e) {
			log.error("浦发->解密异常", e);
		}
		return null;
	}
	
}